const puppeteer = require('puppeteer');
const { targetPath } = require('./storage.config')
var express = require("express"); //加载express构造函数
var { createProxyMiddleware } = require('http-proxy-middleware');
const cors = require('cors');
var bodyParser = require("body-parser");//获取post请求参数
var deleteImage = require('./deleteImage')
var fs = require('fs');
var app = express(); //生成创建服务的实例
//jquery检查连接的url服务是否有效,适用所有浏览器
const $ = require('./jquery');

const path = require('path');
app.use(express.static('public'));//指定资源路径
app.use(bodyParser.json());//处理以json格式的提交


app.use(bodyParser.urlencoded({//处理以form表单的提交
    extended: true
}))
// 使用CORS中间件
app.use(cors({
    origin: '*',
    // origin: ['http://localhost:8080', 'http://127.0.0.1:8081']

}));

app.all("*", function (req, res, next) {
    //设置允许跨域的域名，*代表允许任意域名跨域
    res.header("Access-Control-Allow-Origin", "*");
    //允许的header类型
    res.header("Access-Control-Allow-Headers", "Origin,X-Requested-With,Accept,Content-type");

    res.header("Access-Control-Allow-Credentials", true);
    //跨域允许的请求方式
    res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
    res.header("Content-Type", "application/json;charset=utf-8")
    if (req.method.toLowerCase() == 'options')
        res.sendStatus(200);  //让options尝试请求快速结束
    else
        next();
});

const subTime = (time) => { // 时间戳转日期
    const date = new Date(time)
    const Y = date.getFullYear()
    const M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1
    const D = date.getDate()
    return `${Y}-${M}-${D}`

}

const dirFolder = (folder) => { // 删除制定文件夹
    const folderPath = path.join(__dirname, '/public/image/' + folder); // 文件夹路径
    if (fs.existsSync(folderPath)) {
        fs.readdirSync(folderPath).forEach(file => {
            const curPath = path.join(folderPath, file);
            if (fs.lstatSync(curPath).isDirectory()) {
                // 递归删除子文件夹
                fs.rmdirSync(curPath, { recursive: true });
            } else {
                // 删除文件
                fs.unlinkSync(curPath);
            }
        });
        // 删除空文件夹
        fs.rmdirSync(folderPath);
        console.log(`Folder ${folderPath} has been deleted.`);
    } else {
        console.log(`Folder ${folderPath} does not exist.`);
    }
}

const traverseDir = (dirname) => { // 获取目录下文件夹
    const dirs = [];
    const files = fs.readdirSync(dirname);
    for (let i = 0; i < files.length; i++) {
        const filePath = dirname + '/' + files[i];
        const stat = fs.statSync(filePath);
        if (stat.isDirectory()) {
            dirs.push(files[i]);
            const subDirs = traverseDir(filePath);
            for (let j = 0; j < subDirs.length; j++) {
                dirs.push(files[i] + '/' + subDirs[j]);
            }
        }
    }
    return dirs;
}



const compareData = () => { // 比较日期删除之前的文件夹
    let timer = new Date().getTime()
    let nowDate = subTime(timer) // 当天年月日
    nowTimestamp = new Date(nowDate).getTime() // 转为时间戳
    const folderPath = path.join(__dirname, '/public/image'); // 文件夹路径
    const dirs = traverseDir(folderPath); // 目录下的所有文件夹名称 array

    dirs.forEach((item) => {
        folderTimestamp = new Date(item).getTime()
        if (folderTimestamp < nowTimestamp) {
            dirFolder(item)
        }
    })

}




function myLogger(req, res, next) {

    // console.log('myLogger')
    next()
}

app.use(myLogger)
/* 
    获取图片接口
    @param {String} req.body.url [请求的url地址] 
*/
app.post("/image/respost", function (req, res) {
    // console.log(req.body)//请求的参数对象
    // return
    if (req.body.url == '') {
        res.send({ code: 201, msg: 'url信息为空' })
        return
    }



    try {
        (async () => {
            try {
                var browser = await puppeteer.launch({ headless: false, timeout: 100000 });        //打开浏览器
                // console.log(11111111111)//请求的参数对象

                var page = await browser.newPage();            //新建标签页


            } catch (error) {
                // console.log(error)
                res.json({
                    code: 202,
                    msg: "浏览器错误",
                })
            }

            try {

                await page.goto(req.body.url);

                // return
                await page.setDefaultNavigationTimeout(100000)
                const zoom = await page.$eval('body', e => e.style.zoom = 2);

                // const zoom1 = await page.$eval('.outside', e => e.style.zoom = 2);

                //跳转指定页面
                let time = new Date().getTime()

                // 元素截图
                let body = await page.$('.outside')
                await body.screenshot({
                    path: 'download.png'
                })
                const width = await page.$eval('.outside', e => e.scrollWidth * 2);
                const scrollHeight = await page.$eval('.outside', e => e.scrollHeight * 2);
                await page.setViewport({
                    width: parseInt(width),
                    height: parseInt(scrollHeight)
                });

                fs.mkdir(`./public/image/${subTime(time)}`, { recursive: true }, function (err) {
                    if (err) throw err;
                    console.log('Directory is created successfully.');
                });
                await page.screenshot({                          //截图 默认800x600
                    path: `./public/image/${subTime(time)}/${time}.png`,
                    fullPage: true,
                    omitBackground: false,
                });
                // const width = await page.$eval('.outside', e => e.scrollWidth);
                // const height = await page.$eval('.outside', e => e.scrollHeight);
                // await page.setViewport({
                //     width: parseInt(width) * 2,
                //     height: parseInt(height) * 2
                // });
                // console.log(offsetHeight,'offsetHeight')
                // console.log(height,'height')
                await browser.close();//关闭浏览器
                res.json({
                    code: 1,
                    msg: "截图成功",
                    data: { image: `http://admin.guchelianmeng.com:9999/image/${subTime(time)}/${time}.png`, imagename: `${time}.png` }
                })
            } catch (err) {
                // console.log(req.body,'25')//请求的参数对象

                // await browser.close();//关闭浏览器
                res.json({
                    code: 301,
                    msg: "网址不对",
                })
                // console.log('错误', err)


            }

        })();
    } catch (error) {
        // console.log(error)
        res.json({
            code: 202,
            msg: "浏览器错误",
        })
        // 响应服务器错误
    }


})



app.post("/delete/respost", function (req, res) {
    let time = new Date().getTime()

    console.log('time', time)
    if (req.body.image == '') {
        res.send({ code: 201, msg: '图片不能为空' })
    } else {
        fs.unlink(`./public/image/${subTime(time)}/` + req.body.image, err => {
            if (err) {
                res.send({ code: 202, msg: '删除失败,或文件不存在' })
            } else {
                res.send({ code: 1, msg: '删除文件成功' })

            }
        })
        compareData()
    }


})
function errorHandler(err, req, res, next) {
    res.status(501).json({ error: -1, msg: "错误" })
}


// 对异常的处理 需在请求下边
app.use(errorHandler)

// app.use('/api', createProxyMiddleware({target: 'http://localhost:8081', changeOrigin: true}));
app.listen(9999, () => {
    console.log("启动成功");
})